﻿// /////////////////////////////////// 
//  
//  
//      WiseLink CCF2.0 
//     (c)Copyright 2001-2010 WiseLink Xiaojun (David) Chen 
//        Authored and Owned Xiaojun (David) Chen 
//        All Right Reserved
//  
// /////////////////////////////////// 

using System;
using System.Collections.Generic;
using System.Linq;
using CCF20Model;
using CCF20Model.ModelBase;
using System.Windows.Input;
using CCF20Model.Common.Infrastructure;
using WiseLink.RDS.Resource;
using System.Windows;
using System.Web.Script.Serialization;


namespace CCF20Module
{
    public class CustomerCareViewModel : ObservableObject
    {
        private VehicleModel vehicleModel;
        public CustomerCareViewModel()
        {
            CreateModel();
        }

        private void CreateModel()
        {
            ModelFactory modelFactory = new ModelFactory();
            vehicleModel = (VehicleModel)modelFactory.CreateModel(ModelName.VehicleModel);
            VehicleGridSource = vehicleModel.GetAllVehicles(false).ToList();
        }
        

        private IList<VehicleData> _vehicleGridSource;
        public IList<VehicleData>  VehicleGridSource
        {
            get
            {
                
                return _vehicleGridSource;
            }
            set
            {
                _vehicleGridSource = value;
                RaisePropertyChanged("VehicleGridSource");
            }
        }

        private CustomizeTypeCollection<Fault> _faultGridSource;
        public CustomizeTypeCollection<Fault> FaultGridSource
        {
            get
            {
                return _faultGridSource;
            }
            set
            {
                _faultGridSource = value;
                RaisePropertyChanged("FaultGridSource");
            }
        }

        private CustomizeTypeCollection<ContactHistory> _contactHistoryGridSource;
        public CustomizeTypeCollection<ContactHistory> ContactHistoryGridSource
        {
            get
            {
                return _contactHistoryGridSource;
            }
            set
            {
                _contactHistoryGridSource = value;
                RaisePropertyChanged("ContactHistoryGridSource");
            }
        }

        private CustomizeTypeCollection<SMSHistory> _smsHistoryGridSource;
        public CustomizeTypeCollection<SMSHistory> SMSHistoryGridSource
        {
            get
            {
                return _smsHistoryGridSource;
            }
            set
            {
                _smsHistoryGridSource = value;
                RaisePropertyChanged("SMSHistoryGridSource");
            }
        }

        private VehicleData _currentVehicleData;
        private VehicleData _previousVehicleData;
        private Vehicle _currentVehicle;
        public VehicleData CurrentVehicleData
        {
            get
            {
                return _currentVehicleData;
            }
            set
            {
                if (_currentVehicleData != value)
                {
                    _currentVehicleData = value;
                    if (_currentVehicleData != null)
                    {
                        _previousVehicleData = _currentVehicleData;
                        _currentVehicle = _currentVehicleData.MyVehicle;
                        _currentVehicle.Operator = (string)Application.Current.Properties["CurrentUser"];
                        FaultGridSource = vehicleModel.GetConfirmedFaultByVehicle(_currentVehicle.VehicleID);
                        SMSHistoryGridSource = vehicleModel.GetSMSHistoryByVehicle(_currentVehicle.VehicleID, true);
                        ContactHistoryGridSource = vehicleModel.GetContactHistoryByVehicle(_currentVehicle.VehicleID, true);
                    }
                    else
                    {
                        _faultGridSource = null;
                        _smsHistoryGridSource = null;
                        _contactHistoryGridSource = null;
                    }
                    RaisePropertyChanged("CurrentVehicleData");
                }

            }
        }

        public ICommand CmdRefreshVehicleGrid
        {
            get { return new RelayCommand(RefreshVehicleGrid); }
        }

        private void RefreshVehicleGrid()
        {
            CreateModel();

            if (_previousVehicleData != null)
            {
                ///
                ///Because we have a new datasource, the previous selecteditem is longer findable even the value are the same but the object address is changed.
                ///

                var itemToSelect = VehicleGridSource.AsQueryable().Where(v => v.MyDevice.IDCSimNumber == _previousVehicleData.MyDevice.IDCSimNumber).First();
                if (itemToSelect != null)
                {
                    CurrentVehicleData = itemToSelect;
                }
            }
    
        }


        public ICommand CmdShowContactDialog
        {
            get { return new RelayCommand(ShowContactDialog, IsVehicleSelected); }
        }

        private void ShowContactDialog()
        {
            
            if ((_currentVehicle.LastContactResult != null) && _currentVehicle.LastContactResult.Contains(WiseLinkRDSStatus.Contact_InShop))
            {
                Utility.ShowMessageBox(Message.Care_CantContact_InShop);
                return;
            }
            ContactCustomer contactCustomer = new ContactCustomer(vehicleModel, _currentVehicle);
            contactCustomer.ShowDialog();
        }
        private Boolean IsVehicleSelected()
        {
            if (_currentVehicle != null)
            {
                return true;
            }
            else
            {
                return false;
            }

        }


        public ICommand CmdShowMap
        {
            get { return new RelayCommand(ShowMap, CanShowMap); }
        }

        private void ShowMap()
        {
            
            LoggerHelper.LogCCF20(string.Format("地图请求 VehicleID={0} DeviceID={1}, VehcileLastActiveTime={2}",
                                                        _currentVehicle.VehicleID,
                                                        _currentVehicle.Devices.First().DeviceID,
                                                        _currentVehicle.LatestActiveTime));
            SMSModel.SendShortMessage(_currentVehicle, "位置", "温馨提示模版");
            SMSModel.SendGPRSMessage(_currentVehicle, "位置", "温馨提示模版");
            string ret;
            object[] parameters;
            
            if (ZICMonitorModel.IsJava)
            {
                parameters = new object[]{
                                ZICBase.PID,
                                ZICBase.Pwd,
                                _currentVehicle.Devices.FirstOrDefault().IDCSimNumber,
                                600,//width
                                400};//height
            }
            else
            {
                parameters = new object[] {
                                string.Empty,
                                string.Empty,
                                _currentVehicle.Devices.FirstOrDefault().IDCSimNumber};
            }

            ret = ZICBase.ExectueMethod(ZICMethod.QuerySite, parameters);

            if (ret == null)
            {
                Utility.ShowMessageBox(Message.Care_CantMap_ZICNull);
                return;
            }
            try
            {
                JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
                siteModel model = jsonSerializer.Deserialize<siteModel>(ret); 

                LoggerHelper.LogCCF20(string.Format("查询位置经度={0}, 维度={1}", model.Latitude, model.Longitude));

                HelpMap map = new HelpMap(model);
                map.ShowDialog();

            }
            catch (Exception)
            {
                LoggerHelper.LogCCF20(string.Format("ZIC QuerySite Exception: ZICResponse = {0}", ret));
                Utility.ShowMessageBox(Message.Care_CantMap_ZICError);
                return;
            }


        }
        Boolean CanShowMap()
        {

            if (_currentVehicle != null)
            {
                if (_currentVehicle.Devices.FirstOrDefault().IsSpecialIDC != true)
                {
                    if (_currentVehicle.IsUrgent && DateTime.Now - _currentVehicle.LatestActiveTime < new TimeSpan(1, 0, 0))
                    {
                        return true;

                    }
                    else
                    {

                        return false;
                    }
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return false;
            }


        }

        public ICommand CmdRemoveUrgent
        {
            get { return new RelayCommand(RemoveUrgent, CanRemoveUrgent); }
        }

        private void RemoveUrgent()
        {
            if (Utility.ShowConfirmation(Message.Care_RemvoeUrgent_Confirm))
            {
                vehicleModel.RemoveUrgent(_currentVehicle);
                RefreshVehicleGrid();
            }
        }
        Boolean CanRemoveUrgent()
        {
            if (_currentVehicle != null && _currentVehicle.UrgentCount > 0)
            {
                return true;
            }else
            {
                return false;
            }
        }

        public ICommand CmdRestoreCustomer
        {
            get { return new RelayCommand(RestoreCustomer, CanRestoreCustomer); }
        }

        private void RestoreCustomer()
        {
            vehicleModel.RestoreCustomer(_currentVehicle);
            RefreshVehicleGrid();
        }
        Boolean CanRestoreCustomer()
        {
            if (_currentVehicle != null && _currentVehicle.LastContactResult != null &&
                (_currentVehicle.LastContactResult.Contains(WiseLinkRDSStatus.Contact_Giveup) || _currentVehicle.LastContactResult.Contains(WiseLinkRDSStatus.Contact_Reject)))
            {
                return true;
            }else
            {
                return false;
            }
        }

        public ICommand CmdGiveUpCustomer
        {
            get { return new RelayCommand(GiveUpCustome, CanGiveUpCustomer); }
        }

        private void GiveUpCustome()
        {
            if (Utility.ShowConfirmation(Message.Care_Giveup_Confirm))
            {

                vehicleModel.GiveUpCustomer(_currentVehicle);
                RefreshVehicleGrid();
            }
        }

        Boolean CanGiveUpCustomer()
        {
            if (_currentVehicle != null && _currentVehicle.LastContactResult != null && !_currentVehicle.LastContactResult.Contains(WiseLinkRDSStatus.Contact_Giveup))
            {
                return true;
            }else
            {
                return false;
            }
        }

        public ICommand CmdRejectCustomer
        {
            get { return new RelayCommand(RejectCustomer, CanRejectCustomer); }
        }

        private void RejectCustomer()
        {
            if (Utility.ShowConfirmation(Message.Care_Confirm_Reject))
            {
                vehicleModel.DeclineCustomer(_currentVehicle,WiseLinkRDSStatus.Contact_Reject);
                RefreshVehicleGrid();
            }
        }

        Boolean CanRejectCustomer()
        {
            if (_currentVehicle!= null && !string.IsNullOrEmpty(_currentVehicle.LastContactResult) && !_currentVehicle.LastContactResult.Contains(WiseLinkRDSStatus.Contact_Reject))
            {
                return true;
            }else
            {
                return false;
            }
        }

        public ICommand CmdCustomerWillService
        {
            get { return new RelayCommand(CustomerWillService, IsVehicleSelected); }
        }

        private void CustomerWillService()
        {
            if (Utility.ShowConfirmation(Message.Care_WillService_Confirm))
            {
                vehicleModel.VehicleRepairStart(_currentVehicle, DateTime.Now);
                vehicleModel.VehicleRepairEnd(_currentVehicle, 0, WiseLinkRDSStatus.Contact_WillRepair);
                RefreshVehicleGrid();
            }
        }

        
    }
}
